package com.atguigu.gulimall.order.aop;

import com.atguigu.gulimall.order.annotation.RateLimiter;
import com.atguigu.gulimall.order.exception.RedisLimiterException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.xml.crypto.dsig.SignatureMethod;
import java.lang.reflect.Method;
import java.util.Collections;

/**
 * @Description
 * @Author lhj
 * @Date 2024.5.23 22:07
 */
@Slf4j
@Aspect
@Component
public class RateLimiterAspectj {
    
    @Autowired
    StringRedisTemplate redisTemplate;
    
    DefaultRedisScript<Long> redisScript;
    
    @PostConstruct
    public void init() {
        this.redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/rateLimiter.lua")));
    }
    
    @Pointcut("@annotation(com.atguigu.gulimall.order.annotation.RateLimiter)")
    public void pointCut() {}
    
    
    @Around("pointCut()")
    public Object doLimiter(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("do Limiter");
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        RateLimiter rateLimiter = method.getDeclaredAnnotation(RateLimiter.class);
        if (rateLimiter == null) {
            return joinPoint.proceed();
        }
        String key = rateLimiter.key();
        if (StringUtils.isBlank(key)) {
            throw new RedisLimiterException("annotation key cannot be null!");
        }
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        String redisKey = "order:" + key + ":" + className + "." + methodName;
        Long result = redisTemplate.execute(redisScript, Collections.singletonList(redisKey), String.valueOf(rateLimiter.permitsPerSeconds()), String.valueOf(rateLimiter.expire()));
        if (result == null || result == 0) {
            return rateLimiter.message();
        }
        return joinPoint.proceed();
    } 
    
}
